package com.yunshipei.ui.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;

import com.yunshipei.adapter.TabListAdapter;
import com.yunshipei.common.Globals;
import com.yunshipei.core.manager.TabManager;
import com.yunshipei.core.ui.TabFragment;
import com.yunshipei.core.utils.CommonUtils;
import com.yunshipei.enterplorer.R;
import com.yunshipei.model.HomeAppsBean;
import com.yunshipei.model.LabelListModel;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.YspEvent;
import com.yunshipei.ui.dialog.DialogHelper;

import java.util.ArrayList;
import java.util.List;

import io.rong.eventbus.EventBus;

public class LabelFragment extends Fragment implements View.OnClickListener {

    private static final String ARGS_MAIN_EXTRA_BEAN = "com.yunshipei.enterplorer.main_extra";

    private TextView totalNum;
    private Context mContext;
    private GridView gridView;
    private TabListAdapter tabListAdapter;
    private TextView clearAll;
    private OnLabelInteractionListener mLabelInteractionListener;
    private MainExtraBean mMainExtraBean;

    public static LabelFragment newInstances(MainExtraBean mainExtraBean) {
        LabelFragment labelFragment = new LabelFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARGS_MAIN_EXTRA_BEAN, mainExtraBean);
        labelFragment.setArguments(bundle);
        return labelFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnLabelInteractionListener) {
            mLabelInteractionListener = (OnLabelInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mLabelInteractionListener = null;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        this.mContext = getActivity();
        this.mMainExtraBean = (MainExtraBean) getArguments().getSerializable(ARGS_MAIN_EXTRA_BEAN);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_browser_tab, container, false);
        gridView = (GridView) view.findViewById(R.id.browser_tabs_gv);
        clearAll = (TextView) view.findViewById(R.id.clear_all_tabs);
        clearAll.setOnClickListener(this);
        totalNum = (TextView) view.findViewById(R.id.tab_total_num);
        totalNum.setText(getResources().getString(R.string.opend_label_count, TabManager.getInstance().getSize() + 1));
        if (TabManager.getInstance().getSize() == 0) {
            clearAll.setEnabled(false);
        }
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            //关闭所有窗口的点击事件
            case R.id.clear_all_tabs:
                DialogHelper.clearAllTabDialog(getActivity(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();

                        mLabelInteractionListener.closeAllTabs();
                    }
                });
                break;
            default:
                break;
        }
    }

    private List<LabelListModel> mLabelListModels = new ArrayList<>();

    //刷新UI的函数，在UI数据发生改变的时候调用
    public void onRefresh(int currentActiveTab) {
        TabManager tabManager = TabManager.getInstance();
        mLabelListModels.clear();
        //添加首页的
        mLabelListModels.add(new LabelListModel("首页", mLabelInteractionListener.getHomeWebViewCaptureURL()));
        //添加浏览器的
        for (int i = 0; i < tabManager.getSize(); i++) {
            TabFragment tabFragment = tabManager.getFragment(i);
            if (tabFragment != null) {
                boolean tabDestroy = tabFragment.isViewDestroy();
                LabelListModel labelListModel = new LabelListModel(getTopWebViewTitle(tabFragment), tabFragment.getTabAvatarName(!tabDestroy));
                mLabelListModels.add(labelListModel);
            }
        }
        if (tabListAdapter == null) {
            tabListAdapter = new TabListAdapter(mContext, mLabelListModels, currentActiveTab);
            tabListAdapter.setItemClickListener(new TabItemClickListener());
            gridView.setAdapter(tabListAdapter);
        } else {
            tabListAdapter.notifyDataSetChanged(currentActiveTab);
        }
        totalNum.setVisibility(View.VISIBLE);
        totalNum.setText(getResources().getString(R.string.opend_label_count, tabManager.getSize() + 1));
        if (tabManager.getSize() == 0) {
            clearAll.setEnabled(false);
        } else {
            clearAll.setEnabled(true);
        }
    }

    private String getTopWebViewTitle(TabFragment tabFragment) {
        String title = "无标题";
        List<HomeAppsBean> mHomeApps = mMainExtraBean.getHomeApps();
        if (!tabFragment.isTopWebViewAdapter()) {
            title = tabFragment.getTopItemWebViewTitle();
        } else if (mHomeApps != null) {
            String mUrl = tabFragment.getTopItemOriginUrl();
            String appId = CommonUtils.getUrlParams(mUrl, Globals.WEB_APP_ID);
            if (!TextUtils.isEmpty(appId)) {
                for (HomeAppsBean homeAppsBean : mHomeApps) {
                    if (appId.equals(homeAppsBean.getAppId())) {
                        title = homeAppsBean.getAppName();
                        break;
                    }
                }
            } else {
                String appParentId = CommonUtils.getUrlParams(tabFragment.getStartURL(), Globals.WEB_APP_ID);
                if (!TextUtils.isEmpty(appParentId)) {
                    for (HomeAppsBean homeAppsBean : mHomeApps) {
                        if (appParentId.equals(homeAppsBean.getAppId())) {
                            List<HomeAppsBean> childApps = homeAppsBean.getHomeAppsBeans();
                            if (childApps != null) {
                                for (HomeAppsBean childHomeApp : childApps) {
                                    if (mUrl.equals(childHomeApp.getAppURL())) {
                                        title = childHomeApp.getAppName();
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            }

        }
        return title;
    }

    //下拉刷新更新HomeApps数据
    public void onEventMainThread(YspEvent.UpdateHomeApps updateHomeApps) {
        if (mMainExtraBean != null) {
            mMainExtraBean.setHomeApps(updateHomeApps.getHomeApps());
        }
    }

    //adapter中的点击事件
    private class TabItemClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            int position = (Integer) view.getTag();
            switch (view.getId()) {
                case R.id.thumb:
                case R.id.title:
                    mLabelInteractionListener.onTabHistoryItemClick(false, position);
                    break;
                case R.id.close:
                    mLabelInteractionListener.onTabHistoryItemClick(true, position);
                    break;
            }
        }
    }

    public interface OnLabelInteractionListener {
        void closeAllTabs();

        void onTabHistoryItemClick(boolean isClose, int position);

        String getHomeWebViewCaptureURL();
    }
}
